package ezcaptcha

import (
	"encoding/json"
	"gitee.com/kaylee595/gkaylee/kerr"
	"github.com/imroc/req/v3"
	"net/http"
)

type TaskTypeCloudFlare5sC string

const TaskTypeCloudFlare5sCDefault TaskTypeCloudFlare5sC = "CloudFlare5STask"

// TaskCloudFlare5sC https://ezcaptcha.atlassian.net/wiki/spaces/IS/pages/331612162/CloudFlare5s
type TaskCloudFlare5sC struct {
	Type       TaskTypeCloudFlare5sC `json:"type"`
	WebsiteURL string                `json:"websiteURL"`
	Proxy      string                `json:"proxy"`
	RQData     map[string]any        `json:"rqData,omitempty"`
}

// TaskCloudFlare5sR https://ezcaptcha.atlassian.net/wiki/spaces/IS/pages/331612162/CloudFlare5s
type TaskCloudFlare5sR struct {
	Header     http.Header    `json:"header"`
	Cookies    []*http.Cookie `json:"cookies"`
	Body       string         `json:"body"`
	SToken     string         `json:"sToken"`
	TlsVersion string         `json:"tlsVersion"`
}

func (t *TaskCloudFlare5sR) GetCFClearanceCookie() *http.Cookie {
	const name = "cf_clearance"
	for _, cookie := range t.Cookies {
		if cookie.Name == name {
			return cookie
		}
	}
	return nil
}

func (t *TaskCloudFlare5sR) UnmarshalJSON(data []byte) error {
	s := struct {
		Header     map[string]string `json:"header"`
		Cookies    map[string]string `json:"cookies"`
		Body       string            `json:"body"`
		SToken     string            `json:"sToken"`
		TlsVersion string            `json:"tlsVersion"`
	}{}
	if err := json.Unmarshal(data, &s); err != nil {
		return kerr.WrapTraceStack(err)
	}
	t.Header = make(http.Header, len(s.Header))
	for k, v := range s.Header {
		t.Header.Set(k, v)
	}
	t.Cookies = make([]*http.Cookie, 0, len(s.Cookies))
	for name, value := range s.Cookies {
		t.Cookies = append(t.Cookies, &http.Cookie{Name: name, Value: value})
	}
	t.Body = s.Body
	t.SToken = s.SToken
	t.TlsVersion = s.TlsVersion
	return nil
}

type (
	ClientCloudFlare5s  = Client[TaskCloudFlare5sC, TaskCloudFlare5sR]
	OptionsCloudFlare5s = Option[TaskCloudFlare5sC, TaskCloudFlare5sR]
)

func NewClientForCloudFlare5s(httpClient *req.Client, clientKey string, opts ...OptionsCloudFlare5s) *ClientCloudFlare5s {
	return NewClient(httpClient, clientKey, opts...)
}
